<template>
    <div v-if="editing" @keydown.enter="save" @keydown.esc="cancel">
      <el-input
        ref="input"
        v-model="editedValue"
        size="small"
        @blur="save"
      ></el-input>
    </div>
    <div v-else @dblclick="startEdit">
      <slot></slot>
    </div>
  </template>
  
  <script setup>
  import { ref, nextTick } from 'vue';
  
  const props = defineProps(['modelValue']);
  const emit = defineEmits(['update:modelValue', 'rename']);
  
  const editing = ref(false);
  const editedValue = ref(props.modelValue);
  
  function startEdit() {
    editing.value = true;
    editedValue.value = props.modelValue;
    nextTick(() => {
      document.querySelector('input').focus();
    });
  }
  
  function save() {
    if (editedValue.value !== props.modelValue) {
      emit('rename', editedValue.value);
    }
    editing.value = false;
  }
  
  function cancel() {
    editing.value = false;
  }
  </script>